<!--
 * @Descripttion: 
 * @version: 
 * @Author: 高月飞
 * @Date: 2023-11-15 16:50:09
 * @LastEditors: 高月飞
 * @LastEditTime: 2023-11-25 21:02:02
-->
<!--
 * @Descripttion: 
 * @version: 
 * @Author: 高月飞
 * @Date: 2023-11-15 16:50:09
 * @LastEditors: 高月飞
 * @LastEditTime: 2023-11-16 10:01:47
-->
<template>
    <div>
        <el-form size="default" :model="userAddFormData" status-icon :rules="rules" ref="userAddFormRef" label-width="90px">
            <el-form-item label="姓名" prop="realname">
                <el-input type="text" v-model="userAddFormData.realname" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="账号" prop="username">
                <el-input type="text" v-model="userAddFormData.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-checkbox v-model="isEditPassword" label="是否修改密码" />
                <el-input type="text" v-model="userAddFormData.password" autocomplete="off" v-if="isEditPassword"
                    placeholder="请输入新密码"></el-input>
            </el-form-item>
            <el-form-item label="角色" prop="role">
                <el-select v-model="userAddFormData.role" filterable placeholder="请选择角色">
                    <el-option v-for="item in roles" :key="item.id" :label="item.roleIdentifier" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="userAddFormData.sex">
                    <el-radio label="1">先生</el-radio>
                    <el-radio label="2">女士</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="手机" prop="phone">
                <el-input type="text" v-model="userAddFormData.phone" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
                <el-date-picker type="date" placeholder="选择日期" value-format="YYYY-MM-DD" v-model="userAddFormData.birthday"
                    :disabled-date="disableDateHandle" />
            </el-form-item>
            <el-form-item label="头像">
                <el-upload class="avatar-uploader" action="#" :multiple="false" :show-file-list="false"
                    accept=".jpg,.jpeg,.gif,.png" :before-upload="beforeAvatarUpload">
                    <img v-if="imgUrl" :src="imgUrl" class="avatar" />
                    <el-icon v-else>
                        <Plus />
                    </el-icon>
                    <template #tip>
                        <div class="el-upload__tip">只能上传jpg/png/gif文件，且不超过1MB</div>
                    </template>
                </el-upload>
                <div v-if="imgUrl" @click="deleteAvatar">
                    <el-icon>
                        <Delete />
                    </el-icon>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitAddForm" :loading="loading">提交</el-button>
                <el-button @click="resetAddForm">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
/**
 *配置导入
 * reactive  ，ref
 * 表单实例 ref  和rules
 * 增加用户api
 * 错误信息提示
 * 正确信息提示
 * 指定年份日期
 * 引入修改用户给定的id进行数据的回显的钩子函数
 */
import type { FormInstance, FormRules, UploadRawFile } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { errorMessage } from "@/utils/Tools/errorMessage";
import { successMessage } from "@/utils/Tools/successMessage";
import { getFullYearDay } from "@/utils/Tools/yearAndDate";
import { deleteuploadSystemEmployeeAvatarApi, editUserSystemEmployeeToInfoApi, uploadSystemEmployeeAvatarApi } from "@/services/employee";
import { useUserInfo } from "../empolyeehook";

/**
 * 解析数据
 */
const [dateStr, dateObj] = getFullYearDay(-23)


/**
 * 定义Props
 */
interface IProps {
    setDialogVisible: (visible: boolean) => void
    editUid: number
}

/**
 * 接收props数据
 */
const props = defineProps<IProps>()

/**
 * 获取
 * 表单实例
 * 防抖处理
 * 获取当前时间
 * 定义头像回显
 * 接收是否修改密码
 */
const userAddFormRef = ref<FormInstance>()
const loading = ref(false);
const defaultDateTime = dateObj.valueOf()
const imgUrl = ref("")
const isEditPassword = ref(false)



/**
 * 定义数据
 * 用户数据
 * 角色数据
 */
interface IEmployee {
    username: string;
    password: string;
    realname: string;
    sex: string;
    phone: string;
    birthday: string;
    avatar: string;
    role: number | string;

}
interface IRole {
    id: number
    roleName: string
    roleIdentifier: string
}
interface IUserInfo {
    id?: number
    url?: string
    username?: string;
    realname?: string;
    sex?: string;
    phone?: string;
    birthday?: string;
    avatar?: string;
    role?: number | string;

}
const userAddFormData = reactive({
    realname: '',
    username: '',
    password: '',
    sex: '',
    phone: '',
    birthday: '',
    avatar: '',
    role: ''
})
const roles = ref<IRole[]>([
    { id: 1, roleName: '管理员', roleIdentifier: 'admin' },
    { id: 2, roleName: '编辑员', roleIdentifier: 'edit' },
    { id: 3, roleName: '人事', roleIdentifier: 'hr' }
])

/**
 * 事件处理
 * 增加事件--submitAddForm
 * 重置事件--resetAddForm
 * 上传头像操作---beforeAvatarUpload-----https://blog.csdn.net/superherooooss/article/details/128913294
 * 删除头像
 * 回显数据
 */
const submitAddForm = () => {
    if (!userAddFormRef.value) return
    loading.value = true
    userAddFormRef.value.validate(async valid => {

        if (valid) {
            // 不用修改密码
            if (!isEditPassword.value) {
                // 类型中一定要有password,且它要为可选，才能进行delete
                delete (userAddFormData as Partial<typeof userAddFormData>).password
            }

            let ret = await editUserSystemEmployeeToInfoApi(props.editUid, userAddFormData)
            console.log(ret)
            if (ret.code === 200) {
                successMessage('Modify user successfully', () => {
                    loading.value = false
                    resetAddForm()
                    props.setDialogVisible(false)
                }, 100)
            } else {
                errorMessage('Modify user exception, please resubmit', () => {
                    loading.value = false
                }, 3000)
            }
        } else {
            errorMessage('Form validation failed', () => {
                loading.value = false
            }, 3000)
        }
    })
}
const resetAddForm = () => {
    if (!userAddFormRef.value) return
    userAddFormRef.value.resetFields()
}
const beforeAvatarUpload = async (rawFile: UploadRawFile) => {
    //设置大小
    const size = 10 * 1024 * 1024
    if (rawFile.size > size) {
        errorMessage("The uploaded file is larger than 10MB, please select again", () => { }, 2000)
        return false
    }
    //判断上传之能时图片
    const allowMimeType = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif']
    if (!allowMimeType.includes(rawFile.type)) {
        errorMessage("Only png, jpg, jpeg, gif formats can be uploaded", () => { }, 2000)
        return false
    }

    //上传图片
    const formData = new FormData()
    formData.append('file', rawFile)
    let ret = await uploadSystemEmployeeAvatarApi(formData)
    if (ret.code == 200) {
        imgUrl.value = ret.data.url
        userAddFormData.avatar = ret.data.path
    }
    else {
        errorMessage('Failed to upload avatar', () => { }, 2000)
    }
    return false
}
const deleteAvatar = async () => {
    let ret = await deleteuploadSystemEmployeeAvatarApi(userAddFormData.avatar)
    if (ret.code == 200) {
        imgUrl.value = ""
        userAddFormData.avatar = ""
    }
}

useUserInfo(props.editUid, data => {
    for (let key in userAddFormData) {

        let value = data[key as keyof IUserInfo]
        if (typeof userAddFormData[key as keyof typeof userAddFormData] === "string") {
            userAddFormData[key as keyof typeof userAddFormData] = value as string
        }


    }
    imgUrl.value = data.url!

})


/**
 * 规则验证
 * 验证账号--validateUsername
 * 验证手机号
 * 禁用时间
 * 验证密码
 */
const validateUsername = (rule: any, value: string, callback: any) => {
    if (value === '') {
        callback(new Error('Please input the Username'))
    } else {
        const reg = /^[a-z]{6,10}$/;
        if (!reg.test(value)) {
            callback(new Error('Username must be 6 to 10 characters'))
        }
        else {
            callback()
        }
    }
}
const validatePohone = (rule: any, value: string, callback: any) => {
    if (value === '') {
        callback(new Error('Please input the Phone Number'))
    } else {
        const reg = /^1[2-9]\d{9}$/
        if (!reg.test(value)) {
            callback(new Error('Please enter the correct mobile phone number format'))
        }
        else {
            callback()
        }
    }
}
const disableDateHandle = (date: Date) => {
    return date.getTime() > defaultDateTime
}
const validatePassword = (rule: any, value: string, callback: any) => {
    if (value === '') {
        callback(new Error('Please input the Password'))
    } else {
        const reg = /^[a-z]{6,10}$/;
        if (!reg.test(value)) {
            callback(new Error('Username must be 6 to 10 characters'))
        }
        else {
            callback()
        }
    }
}


/**
 * 注意点---需要放在后面
 * 规则验证
 */
const rules = reactive<FormRules<IEmployee>>({
    realname: [{ required: true, whitespace: true, message: '姓名不能为空', trigger: 'blur' }],
    username: [
        { required: true, whitespace: true, message: '账号不能为空', trigger: 'blur' },
        { validator: validateUsername, trigger: 'blur' }
    ],
    password: [
        { validator: validatePassword, trigger: 'blur' }
    ],
    phone: [{ validator: validatePohone, trigger: 'blur' }]
})

</script>

<style lang="scss" scoped>
:deep(.avatar-uploader) {
    .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        width: 178px;
        height: 178px;
        overflow: hidden;
    }

    .el-upload:hover {
        border-color: #409eff;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>